package movee.utils.collection;

import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 *
 *
 * @author movee
 */
public final class CollectionUtil {

    private CollectionUtil() { }

    /**
     * 根据指定子数组的大小分割数据集合
     * @param origin origin
     * @param size 子数组大小
     * @param <T> T
     * @return list
     */
    public static  <T> List<List<T>> splitListBySize(Collection<T> origin, int size) {

        Assert.isTrue(size > 0, "size must be more than zero");

        List<List<T>> result = new ArrayList<>();
        if (CollectionUtils.isEmpty(origin)) {
            return result;
        }

        List<T> slice = new ArrayList<>();
        int count = 0;
        for (T item : origin) {
            if (count >= size) {
                result.add(slice);
                slice = new ArrayList<>();
                count = 0;
            }

            slice.add(item);
            count++;
        }

        if (!slice.isEmpty()) {
            result.add(slice);
        }

        return result;
    }

    /**
     * 根据指定子数组的数量分割数据集合
     * @param origin origin
     * @param count 子数组数量
     * @param <T> T
     * @return list
     */
    public static  <T> List<List<T>> splitListByCount(Collection<T> origin, int count) {

        Assert.isTrue(count > 0, "size must be more than zero");

        if (CollectionUtils.isEmpty(origin)) {
            return new ArrayList<>();
        }

        int size = origin.size() / count;
        size = (origin.size() % count) == 0 ? size : size + 1;

        return splitListBySize(origin, size);
    }
}
